package com.odobenus.client.processor;

import java.util.Properties;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import com.odobenus.client.anno.OdobenusFile;
import com.odobenus.client.properties.OdobenusProperties;
import com.odobenus.client.tools.BeanUtils;


public class OdobenusClientBeanPostProcessor implements BeanPostProcessor {
	private OdobenusProperties odobenusProperties;

	public void setOdobenusProperties(OdobenusProperties odobenusProperties) {
		this.odobenusProperties = odobenusProperties;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		Class<?> objClz;
		if (AopUtils.isAopProxy(bean)) {
			objClz = AopUtils.getTargetClass(bean);
		} else {
			objClz = bean.getClass();
		}
		try {
			if (objClz.isAnnotationPresent(OdobenusFile.class)) {
				OdobenusFile odobenusFile = objClz.getAnnotation(OdobenusFile.class);
				String filePath = odobenusFile.value();
				if (odobenusProperties.getEnableRemote()&&!"apollo".equals(odobenusProperties.getMode())) {
					BeanUtils.downloadFile(odobenusProperties, filePath);
				}
				Properties props = BeanUtils.load(odobenusProperties, filePath);
				BeanUtils.changeFieldValue(props, bean, objClz.getDeclaredFields());
			}else if(odobenusProperties.getEnableRemote()&&"apollo".equals(odobenusProperties.getMode())) {
				BeanUtils.downloadFile(odobenusProperties, "apollo.properties");
			}

		} catch (Exception e) {
			throw new BeanCreationException(beanName, e);
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

}
